/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs: 自绘开发板IO控制
 * Date           Author       Notes
 * 2023-05-30     Administrator       the first version
 */
#include <rtthread.h>
#include <rtdevice.h>
#include "drv_gpio.h"
#include <hal.h>

//#define BEEP   GET_PIN(E, 5) // PWM 响
//#define LED0   GET_PIN(E, 9) // 高电平亮
//#define BKPWM  GET_PIN(E, 6) // PWM 控制亮度
#define BEEP  GPIO_PORT_E,GPIO_PIN_5 // PWM 响  这个IO不是PWM 口
#define LED0  GPIO_PORT_E,GPIO_PIN_9 // 高电平亮
#define BKPWM GPIO_PORT_E,GPIO_PIN_6 // PWM 控制亮度

#define PWM_DEV_NAME        "pwm1"  /* PWM设备名称 */
#define PWM_DEV_CHANNEL     1       /* PWM通道 */
struct  rt_device_pwm *pwm_dev;      /* PWM设备句柄 */

//初始化 IO状态

void beep_on(){
//  rt_kprintf("turn on beep!\n");
    gpio_direction_output(LED0,1);
}
void beep_off(){
//  rt_kprintf("turn off beep!\n");
    gpio_direction_output(LED0,0);
}
void led_on(){
//    rt_kprintf("turn on led!\n");
    gpio_direction_output(LED0,1);
}
void led_off(){
//    rt_kprintf("turn off led!\n");
    gpio_direction_output(LED0,0);
}

// IO PIN 任务
static void io_output_thread(void *parameter){
    gpio_set_func(LED0,IO_OUTPUT);
    gpio_set_func(BEEP,IO_OUTPUT);
    gpio_set_func(BKPWM,IO_FUN_3); // 设置为PWM 模式


    rt_uint32_t period, pulse;
    period = 500000;    /* 周期为0.5ms，单位为纳秒ns */
    pulse =  2500;          /* PWM脉冲宽度值，单位为纳秒ns */
    /* 查找设备 */
    pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
    /* 设置PWM周期和脉冲宽度 */
    rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);
    /* 使能设备 */
    rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);

    while (1){
        led_on();
        rt_thread_mdelay(1000);
        led_off();
        rt_thread_mdelay(1000);
    }
}
// 创建一个 IO输出的 线程线程初始化
static int hal_io_init(void){
    rt_thread_t tid;
    tid = rt_thread_create("HAL_IO", io_output_thread, RT_NULL, 4096,10,10);
    if (tid == RT_NULL){
        rt_kprintf("Fail to create 'HAL_IO' thread\n");
    }
    rt_thread_startup(tid);
    return 0;
}
INIT_APP_EXPORT(hal_io_init);
